//
//  ListBoot.swift
//  SwiftUIWidgetDemo
//
//  Created by alanzhangg on 2023/7/15.
//

import SwiftUI

struct ListBoot: View {
    
    @State var fruits: [String] = [
        "apples", "orange", "banana", "peach"
    ]
    
    @State var veggies: [String] = [
        "tomato", "photo", "carrot"
    ]
    
    var body: some View {
        NavigationView{
            List {
                Section {
                    ForEach(fruits, id: \.self) { fruit in
                        Text(fruit.capitalized)
                    }
                    .onDelete(perform: delete)
                    .onMove(perform: move)
                    //                .onDelete(perform: { indexSet in
                    //                    delete(indexSet: indexSet)
                    //                })
                } header: {
                    Text("Fruits")
                        .font(.headline)
                        .foregroundStyle(.purple)
                }
                
                Section {
                    ForEach(veggies, id: \.self) { veggie in
                        Text(veggie.capitalized)
                    }
                } header: {
                    Text("Veggies")
                }

                
            }
            .listStyle(InsetListStyle())
            .navigationTitle("Grocery")
            .toolbar(content: {
                ToolbarItem(placement: .topBarLeading) {
                    EditButton()
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button("add") {
                        add()
                    }
                }
            })
        }
    }
    
    func delete(indexSet: IndexSet) {
        fruits.remove(atOffsets: indexSet)
    }
    func move(indices: IndexSet, newOffset: Int){
        fruits.move(fromOffsets: indices, toOffset: newOffset)
    }
    
    func add(){
        fruits.append("Ccoconut")
    }
}

#Preview {
    ListBoot()
}
